import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterdemo/1demo/network/http_manager.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class DownloadPage extends StatefulWidget {
  @override
  _DownloadPageState createState() => _DownloadPageState();
}

class _DownloadPageState extends State<DownloadPage> with DownloadCallback {
  double _progress = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("download"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: _storagePermission,
              child: Text("下载文件"),
            ),
            FlatButton(
//              onPressed: _callKotlin,
              onPressed: _callKotlin,
              child: Text("调用原生android"),
            ),
            FlatButton(
//              onPressed: _callKotlin,
              onPressed: _getBatteryLevel,
              child: Text("调用原生android获取电量"),
            ),
            SizedBox(
              height: 20,
            ),
            Text("进度:$_progress"),
          ],
        ),
      ),
    );
  }

  Future<void> _storagePermission() async {
    if (Platform.isIOS) {
      Fluttertoast.showToast(
        msg: "IOS去APP Store下载",
        backgroundColor: Colors.black,
        textColor: Colors.redAccent,
      );
      return;
    }
    bool isPermissionGranted = await _permissionCheck();
    if (isPermissionGranted) {
      Fluttertoast.showToast(
        msg: "已有该权限",
        backgroundColor: Colors.black,
        textColor: Colors.redAccent,
      );
      _download();
    } else {
      // 申请权限
      print("申请权限");
      _requestPermission().then((isGranted) {
        if (isGranted) {
          Fluttertoast.showToast(msg: "权限申请成功", backgroundColor: Colors.black54);
          _download();
        } else {
          Fluttertoast.showToast(msg: "权限申请拒绝");
        }
      });
    }
  }

  Future<bool> _permissionCheck() async {
    return await Permission.storage.isGranted;
  }

  Future<bool> _requestPermission() async {
    PermissionStatus permissionStatus = await Permission.storage.request();
    if (permissionStatus.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  Future<void> _download() async {
    String url = "http://gdown.baidu.com/data/wisegame/bab5d3dad331fa7c/1e2cbab5d3dad331fa7c8113b4c73786.apk";
    String fileName = "yyb.apk";
    String savePath = await getPhoneLocalPath();
    HttpManager.getInstance().downloadFile(url, fileName, savePath, this);
  }

  ///获取手机的存储目录路径
  ///getExternalStorageDirectory() 获取的是  android 的外部存储 （External Storage）
  ///  getApplicationDocumentsDirectory 获取的是 ios 的Documents` or `Downloads` 目录
  Future<String> getPhoneLocalPath() async {
    final directory = Theme.of(context).platform == TargetPlatform.android
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory.path;
  }

  @override
  onDownloadComplete(String filePath) {
    print("download complete filePath == $filePath");
    if (Platform.isAndroid) {
      // 安装得调原生
      _installApkByNature(filePath);
    }
  }

  @override
  onDownloadFail(Exception exception) {
    print("download fail exception == $exception");
  }

  @override
  onDownloading(int progress) {
    _sendNotification(progress);
    print("downloading progress == $progress");
  }

  @override
  onDownloadStart() {

  }

  Future<void> _callKotlin() async {
    // flutter call native and get return
    const methodChannel = const MethodChannel("top.tupobi.flutterdemo/test");
    // "getData"是调用的方法名；param是getData的参数，可以不传参
    Map<String, dynamic> param = {'name': 'demo', 'age': 2};
    try{
      final String data = await methodChannel.invokeMethod<String>("getData", param);
      print("data == $data");
    }on PlatformException catch(e){
      print("catch exception" * 5 + e.message);
    }
  }

  Future<void> _getBatteryLevel() async {
    const methodChannel = const MethodChannel("top.tupobi.flutterdemo/test");
    // "getData"是调用的方法名；param是getData的参数，可以不传参
    Map<String, dynamic> param = {'name': 'demo', 'age': 2};
    try{
      final int data = await methodChannel.invokeMethod<int>("getBatteryLevel", param);
      print("data == $data");
    }on PlatformException catch(e){
      print("catch exception" * 5 + e.message);
    }
  }

  Future<void> _installApkByNature(String filePath) async {
    const methodChannel = const MethodChannel("top.tupobi.flutterdemo/test");
    try{
      Map<String, dynamic> params = {'filePath': filePath};
      final int res = await methodChannel.invokeMethod<int>("installApk", params);
      if(res == 1){
        print("安装完成");
      }else{
        print("安装失败");
      }
    }on PlatformException catch(e){
      print("catch exception" * 5 + e.message);
    }
  }

  Future<void> _sendNotification(int progress) async {
    const methodChannel = const MethodChannel("top.tupobi.flutterdemo/test");
    try{
      Map<String, dynamic> params = {'progress': progress};
      await methodChannel.invokeMethod<int>("sendNotification", params);
    }on PlatformException catch(e){
      print("catch exception" * 5 + e.message);
    }
  }

}
